//
//  XMInviteViewController.m
//  XunMi
//
//  Created by MacBook on 2024/3/12.
//  Copyright © 2024 TieZhu. All rights reserved.
//

#import "XMInviteViewController.h"
#import "XMInviteTableViewCell1.h"
#import "XMXMInviteTableViewCell2.h"
#import "XMXMInviteTableViewCell3.h"
#import "XMInviteCollectionViewCell.h"
#import "XMInviteRuleView.h"
#import "XMInviteShareView.h"
#import "XMShareModel.h"
#import "XMSaveInviteView.h"
#import <Photos/Photos.h>
#import "XMWXApiManager.h"
//#import <TencentOpenAPI/QQApiInterfaceObject.h>
//#import "TencentOpenAPI/QQApiInterface.h"
#import <TencentOpenAPI/TencentOpenApiUmbrellaHeader.h>
#import <TencentOpenAPI/TencentOAuth.h>
#import "XMInviteModel.h"
#import "XMRealTipView.h"
#import "XMRealViewController.h"
#import "XMInviteRedResultView.h"

@interface XMInviteViewController ()<UITableViewDelegate, UITableViewDataSource, UICollectionViewDelegate, UICollectionViewDataSource, UIScrollViewDelegate>

@property (weak, nonatomic) IBOutlet UIScrollView *scrollerView;
@property (weak, nonatomic) IBOutlet UILabel *ruleLa;
@property (weak, nonatomic) IBOutlet UIView *rileBgView;

@property (weak, nonatomic) IBOutlet UILabel *friendReLa;
@property (weak, nonatomic) IBOutlet UILabel *frienIncomLa;
@property (weak, nonatomic) IBOutlet UILabel *friendTipLa;

@property (weak, nonatomic) IBOutlet UILabel *redLeftLa;
@property (weak, nonatomic) IBOutlet UILabel *redMidLa;
@property (weak, nonatomic) IBOutlet UILabel *redRightLa;

@property (weak, nonatomic) IBOutlet UILabel *redPeopleNumLa;

@property (weak, nonatomic) IBOutlet UILabel *redLeftStatusLa;
@property (weak, nonatomic) IBOutlet UILabel *redMidStatusLa;
@property (weak, nonatomic) IBOutlet UILabel *redRightStatusLa;

@property (weak, nonatomic) IBOutlet UILabel *redLeftNumLa;
@property (weak, nonatomic) IBOutlet UILabel *redMidNumLa;
@property (weak, nonatomic) IBOutlet UILabel *redRightNumLa;

@property (weak, nonatomic) IBOutlet UILabel *codeLa;

@property (weak, nonatomic) IBOutlet UILabel *timeLa;
@property (weak, nonatomic) IBOutlet UILabel *activeDescLa;

@property (weak, nonatomic) IBOutlet UIButton *incomeDetailBtn;
@property (weak, nonatomic) IBOutlet UIButton *inviteNumBtn;
@property (weak, nonatomic) IBOutlet UILabel *leftLa;
@property (weak, nonatomic) IBOutlet UILabel *rightLa;

@property (weak, nonatomic) IBOutlet UIButton *redLeftBtn;
@property (weak, nonatomic) IBOutlet UIButton *redMidBtn;
@property (weak, nonatomic) IBOutlet UIButton *redRighttBtn;


@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet UITableView *tableView1;
@property (weak, nonatomic) IBOutlet UITableView *tableView2;
@property (weak, nonatomic) IBOutlet UITableView *tableView3;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *tableViewH1;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *tableViewH2;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bgViewH;

@property (weak, nonatomic) IBOutlet UIView *botBgView;

@property (weak, nonatomic) IBOutlet UILabel *noDataLa;
@property (weak, nonatomic) IBOutlet UIImageView *lineImgV;

@property (nonatomic, strong) XMInviteRuleView *inviteRuleView;
@property (nonatomic, strong) XMInviteShareView *inviteShareView;
@property (nonatomic, strong) XMShareModel *shareModel;
@property (nonatomic, strong) XMSaveInviteView *saveView;

@property (nonatomic, strong) QQApiObject *qqApiObject;

@property (nonatomic, strong) XMInviteModel *model;

@property (nonatomic, strong) NSMutableArray <XMUserModel *> *dataArray;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, copy) NSString *prevIndex;
@property (nonatomic, assign) CGFloat tableViewH;
@property (nonatomic, assign) CGFloat collectH;

@property (nonatomic, strong) XMRealTipView *realTipView;
@property (nonatomic, strong) XMInviteRedResultView *redResultView;


@end

@implementation XMInviteViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initVariables];
    [self setupSubviews];
    [self shareData];
    [self inviteData];
    [self viewBlock];
    [kWXApiManager registerAppKey];
    [TencentOAuth setIsUserAgreedAuthorization:YES];
    [[TencentOAuth alloc] initWithAppId:kQQAppId andDelegate:nil]; //注册
}

#pragma mark - 初始化变量
- (void)initVariables {
    self.page = 1;
    self.prevIndex = @"0";
    self.dataArray = [NSMutableArray array];
    
    [self.tableView1 registerNib:kNibWithName(kStringFromClass(XMInviteTableViewCell1)) forCellReuseIdentifier:kStringFromClass(XMInviteTableViewCell1)];
    [self.tableView2 registerNib:kNibWithName(kStringFromClass(XMXMInviteTableViewCell2)) forCellReuseIdentifier:kStringFromClass(XMXMInviteTableViewCell2)];
    [self.tableView3 registerNib:kNibWithName(kStringFromClass(XMXMInviteTableViewCell3)) forCellReuseIdentifier:kStringFromClass(XMXMInviteTableViewCell3)];
    
    [self.collectionView registerNib:kNibWithName(kStringFromClass(XMInviteCollectionViewCell)) forCellWithReuseIdentifier:kStringFromClass(XMInviteCollectionViewCell)];
}

- (void)shareData {
    NSMutableDictionary *dic = @{}.mutableCopy;
    [YHNetworkManager.sharedInstance postWithUrl:@"api/user/poster" parameters:dic completeBlock:^(XMResponseTip * _Nonnull tip, id  _Nullable result) {
        if (tip.success) {
            self.shareModel = [XMShareModel mj_objectWithKeyValues:result];
            NSString *code = kStringFormat(@"邀请码：%@",self.shareModel.invite_code);
            NSMutableAttributedString *codeAtt = [[NSMutableAttributedString alloc] initWithString:code];
            [codeAtt addAttribute:NSForegroundColorAttributeName value:kHEX(@"#FF4D39") range:[code rangeOfString:self.shareModel.invite_code]];
            self.codeLa.attributedText = codeAtt;
            
            [self.saveView.imgView sd_setImageWithURL:kStringToUrl(self.shareModel.poster_link)];
            
            [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:kStringToUrl(self.shareModel.icons) completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
                self.shareModel.share_image = image;
            }];
        }
    }];
}

- (void)inviteUserListDataRefresh {
    self.page = 1;
    self.prevIndex = @"0";
    [self.dataArray removeAllObjects];
    [self inviteUserList];
}

- (void)inviteUserList {
    NSMutableDictionary *dic = @{
        @"page_no": @(self.page),
        @"page_size": @(10),
        @"page_index": self.prevIndex
    }.mutableCopy;
    
    [YHNetworkManager.sharedInstance postWithUrl:@"api/activity/invite/record" parameters:dic completeBlock:^(XMResponseTip * _Nonnull tip, id  _Nullable result) {
        if (tip.success) {
            self.prevIndex = tip.prevIndex;
            NSArray *record = [result safe_objectForKey:@"record"];
            NSArray *array = [XMUserModel mj_objectArrayWithKeyValuesArray:record];
            [self.dataArray addObjectsFromArray:array];
            
            if (self.dataArray.count == 0) {
                self.tableView3.hidden = YES;
                self.collectionView.hidden = YES;
                self.noDataLa.hidden = NO;
                self.tableViewH = 120;
                self.collectH = 120;
                self.bgViewH.constant = 300;
            } else {
                self.tableView3.hidden = NO;
                self.collectionView.hidden = YES;
                self.noDataLa.hidden = YES;
                
                self.tableViewH = self.dataArray.count * 40;
                double number = self.dataArray.count / 3.0;
                double roundedNumber = ceil(number);
                self.collectH = roundedNumber * 110 + (roundedNumber - 1) * 0;
                
                self.bgViewH.constant = self.tableViewH + 180;
                
                [self.tableView3 reloadData];
                [self.collectionView reloadData];
            }
            
            [self.scrollerView.mj_header endRefreshing];
            self.scrollerView.mj_footer.hidden = self.dataArray.count == 0;
            if (tip.loadMore) {
                [self.scrollerView.mj_footer endRefreshing];
            } else {
                [self.scrollerView.mj_footer endRefreshingWithNoMoreData];
            }
        }
    }];
}

- (void)inviteData {
    [MBProgressHUD showHUDActivityMsg:nil toView:kWindow];
    NSMutableDictionary *dic = @{}.mutableCopy;
    [YHNetworkManager.sharedInstance postWithUrl:@"api/activity/invite/config" parameters:dic completeBlock:^(XMResponseTip * _Nonnull tip, id  _Nullable result) {
        if (tip.success) {
            [MBProgressHUD hideHUD];
            XMInviteModel *model = [XMInviteModel mj_objectWithKeyValues:result];
            self.model = model;
            
            self.friendReLa.text = model.recharge_income;
            self.frienIncomLa.text = model.consumed_income;
            
            
            self.timeLa.text = model.activity_config.content.period;
            
            if (model.activity_config.content.level.intValue < 4) {
                NSString *str0 = kStringFormat(@"%@人", model.activity_config.content.user_invite);
                NSString *str1 = kStringFormat(@"等级%@", model.activity_config.content.level);
                NSString *str2 = kStringFormat(@"%@人", model.activity_config.content.need_invite);
                NSString *str3 = kStringFormat(@"等级%@", model.activity_config.content.next_level);
                
                NSString *descStr = kStringFormat(@"您当前邀请认证人数为%@，当前为%@再邀请%@用户认证升为%@", str0, str1, str2, str3);
                NSMutableAttributedString *descAtt = [[NSMutableAttributedString alloc] initWithString:descStr];
                
                [descAtt addAttribute:NSForegroundColorAttributeName value:kHEX(@"#F13519") range:[descStr rangeOfString:str0]];
                [descAtt addAttribute:NSForegroundColorAttributeName value:kHEX(@"#F13519") range:[descStr rangeOfString:str1]];
                [descAtt addAttribute:NSForegroundColorAttributeName value:kHEX(@"#F13519") range:[descStr rangeOfString:str2]];
                [descAtt addAttribute:NSForegroundColorAttributeName value:kHEX(@"#F13519") range:[descStr rangeOfString:str3]];
                
                NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
                paragraphStyle.alignment = NSTextAlignmentLeft;
                paragraphStyle.lineSpacing = 8;
                [descAtt addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, descAtt.length)];
                self.activeDescLa.attributedText = descAtt;
            } else {
                NSString *str0 = kStringFormat(@"%@人", model.activity_config.content.user_invite);
                NSString *str1 = kStringFormat(@"等级%@", model.activity_config.content.level);
                NSString *descStr = kStringFormat(@"您当前邀请认证人数为%@，当前为%@", str0, str1);
                NSMutableAttributedString *descAtt = [[NSMutableAttributedString alloc] initWithString:descStr];
                
                [descAtt addAttribute:NSForegroundColorAttributeName value:kHEX(@"#F13519") range:[descStr rangeOfString:str0]];
                [descAtt addAttribute:NSForegroundColorAttributeName value:kHEX(@"#F13519") range:[descStr rangeOfString:str1]];
                
                NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
                paragraphStyle.alignment = NSTextAlignmentLeft;
                paragraphStyle.lineSpacing = 8;
                [descAtt addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, descAtt.length)];
                self.activeDescLa.attributedText = descAtt;
            }
            
#pragma mark - 红包福利
            NSString *inviter = kStringFormat(@"%@人", model.benefits_config.inviter);
            NSString *inviterStr = kStringFormat(@"当前邀请好友，已有%@完成提现",inviter);
            NSMutableAttributedString *inviterAtt = [[NSMutableAttributedString alloc] initWithString:inviterStr];
            [inviterAtt addAttribute:NSForegroundColorAttributeName value:kHEX(@"#F13519") range:[inviterStr rangeOfString:inviter]];
            self.redPeopleNumLa.attributedText = inviterAtt;
            
            XMBenefits_configContent *bModel0 = [model.benefits_config.content safe_objectAtIndex:0];
            self.redLeftNumLa.text = kStringFormat(@"邀请%@人", bModel0.users);
            
            NSString *bStr0 = kStringFormat(@"%@元", bModel0.money);
            NSMutableAttributedString *bStr0Att = [[NSMutableAttributedString alloc] initWithString:bStr0];
            [bStr0Att addAttribute:NSFontAttributeName value:kUIFont(12) range:[bStr0 rangeOfString:@"元"]];
            self.redLeftLa.attributedText = bStr0Att;
            //领取奖励状态 0 不可领 1可以领 2已领取
            if (bModel0.state.intValue == 0) {
                self.redLeftStatusLa.text = @"未完成";
                self.redLeftNumLa.textColor = kHEX(@"#676767");
                [self.redLeftBtn setBackgroundImage:kGetImage(@"invite_ling0") forState:UIControlStateNormal];
                
            } else if (bModel0.state.intValue == 1) {
                self.redLeftStatusLa.text = @"点击领取";
                self.redLeftNumLa.textColor = kHEX(@"#FF2323");
                [self.redLeftBtn setBackgroundImage:kGetImage(@"invite_ling1") forState:UIControlStateNormal];
                
            } else if (bModel0.state.intValue == 2) {
                self.redLeftStatusLa.text = @"已领取";
                self.redLeftNumLa.textColor = kHEX(@"#FF2323");
                [self.redLeftBtn setBackgroundImage:kGetImage(@"invite_ling2") forState:UIControlStateNormal];
            } else if (bModel0.state.intValue == 2) {
                self.redLeftStatusLa.text = @"领取中";
                self.redLeftNumLa.textColor = kHEX(@"#FF2323");
                [self.redLeftBtn setBackgroundImage:kGetImage(@"invite_ling1") forState:UIControlStateNormal];
            }
            
            XMBenefits_configContent *bModel1 = [model.benefits_config.content safe_objectAtIndex:1];
            
            self.redMidNumLa.text = kStringFormat(@"邀请%@人", bModel1.users);
            
            NSString *bStr1 = kStringFormat(@"%@元", bModel1.money);
            NSMutableAttributedString *bStr1Att = [[NSMutableAttributedString alloc] initWithString:bStr1];
            [bStr1Att addAttribute:NSFontAttributeName value:kUIFont(12) range:[bStr1 rangeOfString:@"元"]];
            self.redMidLa.attributedText = bStr1Att;
            //领取奖励状态 0 不可领 1可以领 2已领取
            if (bModel1.state.intValue == 0) {
                self.redMidStatusLa.text = @"未完成";
                self.redMidNumLa.textColor = kHEX(@"#676767");
                [self.redMidBtn setBackgroundImage:kGetImage(@"invite_ling0") forState:UIControlStateNormal];
                
            } else if (bModel1.state.intValue == 1) {
                self.redMidStatusLa.text = @"点击领取";
                self.redMidNumLa.textColor = kHEX(@"#FF2323");
                [self.redMidBtn setBackgroundImage:kGetImage(@"invite_ling1") forState:UIControlStateNormal];
                
            } else if (bModel1.state.intValue == 2) {
                self.redMidStatusLa.text = @"已领取";
                self.redMidNumLa.textColor = kHEX(@"#FF2323");
                [self.redMidBtn setBackgroundImage:kGetImage(@"invite_ling2") forState:UIControlStateNormal];
            }
            
            XMBenefits_configContent *bModel2 = [model.benefits_config.content safe_objectAtIndex:2];
            
            self.redRightNumLa.text = kStringFormat(@"邀请%@人", bModel2.users);
            
            NSString *bStr2 = kStringFormat(@"%@元", bModel2.money);
            NSMutableAttributedString *bStr2Att = [[NSMutableAttributedString alloc] initWithString:bStr2];
            [bStr2Att addAttribute:NSFontAttributeName value:kUIFont(12) range:[bStr2 rangeOfString:@"元"]];
            self.redRightLa.attributedText = bStr2Att;
            //领取奖励状态 0 不可领 1可以领 2已领取
            if (bModel2.state.intValue == 0) {
                self.redRightStatusLa.text = @"未完成";
                self.redRightNumLa.textColor = kHEX(@"#676767");
                [self.redRighttBtn setBackgroundImage:kGetImage(@"invite_ling0") forState:UIControlStateNormal];
                
            } else if (bModel2.state.intValue == 1) {
                self.redRightStatusLa.text = @"点击领取";
                self.redRightNumLa.textColor = kHEX(@"#FF2323");
                [self.redRighttBtn setBackgroundImage:kGetImage(@"invite_ling1") forState:UIControlStateNormal];
                
            } else if (bModel2.state.intValue == 2) {
                self.redRightStatusLa.text = @"已领取";
                self.redRightNumLa.textColor = kHEX(@"#FF2323");
                [self.redRighttBtn setBackgroundImage:kGetImage(@"invite_ling2") forState:UIControlStateNormal];
            }
            
            XMActivity_configList *model0 = [[XMActivity_configList alloc] init];
            model0.index = @"等级";
            model0.label = @"邀请认证人数";
            model0.award = @"收益奖励";
            model0.state = @(0);
            [self.model.activity_config.content.config_list insertObject:model0 atIndex:0];
            self.tableViewH1.constant = self.model.activity_config.content.config_list.count * 40;
            [self.tableView1 reloadData];
            self.tableView1.hidden = model.activity_config.status.intValue == 0;
            
            [self.tableView2 reloadData];
            
            self.leftLa.attributedText = [self leftAttr:model.invitation_data.today.invite_money point:kStringFormat(@"%@积分", model.invitation_data.today.invite_score) type:@"今日收益："];
            
            self.rightLa.attributedText = [self leftAttr:model.invitation_data.total.invite_money point:kStringFormat(@"%@积分", model.invitation_data.total.invite_score) type:@"总收益："];
            
            [self inviteUserList];
        }
    }];
}

#pragma mark - setupSubViews
- (void)setupSubviews {
    [self.navView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.top.equalTo(self.view);
        make.height.offset(kNavBarAndStatusBarHeight);
        make.right.equalTo(self.view).offset(-100);
    }];
    
    self.navView.backgroundColor = UIColor.clearColor;
    [self.navLeftBtn setImage:kGetImage(@"xm_arrow_back_w") forState:UIControlStateNormal];
    
    [self.botBgView radiusWithRadius:20 corner:UIRectCornerTopLeft | UIRectCornerTopRight];
    [self.rileBgView radiusWithRadius:15 corner:UIRectCornerTopLeft | UIRectCornerBottomLeft];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showInviteRuleView)];
    [self.rileBgView addGestureRecognizer:tap];
    
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake((kScreenWidth - 80) / 3, 110);
    flowLayout.minimumLineSpacing = 0;
    flowLayout.minimumInteritemSpacing = 0;
    [self.collectionView setCollectionViewLayout:flowLayout];
    
    [self.view bringSubviewToFront:self.rileBgView];
    
    self.tableView1.layer.borderColor = kHEX(@"#E0E0E0").CGColor;
    self.tableView1.layer.borderWidth = 1;
    
    NSString *noDataStr = @"快去邀请好友领取现金吧~";
    NSMutableAttributedString *noDataAtt = [[NSMutableAttributedString alloc] initWithString:noDataStr];
    
    NSRange range = [noDataStr rangeOfString:@"邀请好友"];
    
    [noDataAtt addAttribute:NSUnderlineStyleAttributeName
                      value:@(NSUnderlineStyleSingle)
                      range:range];
    [noDataAtt addAttribute:NSForegroundColorAttributeName value:kHEX(@"#F41414") range:range];
    [noDataAtt addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"PingFangSC-Medium" size:16] range:range];
    [noDataAtt addAttribute:NSUnderlineColorAttributeName value:kHEX(@"#F41414") range:range];
    self.noDataLa.attributedText = noDataAtt;
    
    NSString *tipStr = @"好友完成任意充值/收益，奖励即时发送到账户";
    NSMutableAttributedString *tipAttStr = [[NSMutableAttributedString alloc] initWithString:@"好友完成任意充值/收益，奖励即时发送到账户"];
    
    [tipAttStr addAttributes:@{NSForegroundColorAttributeName: kHEX(@"#FFF3A8")} range:[tipStr rangeOfString:@"完成任意充值/收益"]];
    
    self.friendTipLa.attributedText = tipAttStr;
    
    self.scrollerView.delegate = self;
    
    XMWeakSelf(self);
    [[[XMRefreshNormalHeader headerWithRefreshingBlock:^{
        XMStrongSelf(self);
        [self inviteUserListDataRefresh];
        
    }] linkTo:self.scrollerView] autoChangeTransparency:YES];
    
    
    [[[XMRefreshBackFooter footerWithRefreshingBlock:^{
        XMStrongSelf(self);
        self.page += 1;
        [self inviteUserListDataRefresh];
        
    }] linkTo:self.scrollerView] autoChangeTransparency:YES];
    self.scrollerView.mj_footer.hidden = YES;
    
    self.noDataLa.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showInviteShareView)];
    [self.noDataLa addGestureRecognizer:tap1];
}

- (NSMutableAttributedString *)leftAttr:(NSString *)money point:(NSString *)point type:(NSString *)type {
    NSString *str1 = @"≈ ";
    NSString *str2 = @"元";
    
    NSString *str;
    if (money.floatValue > 0) {
        str = kStringFormat(@"%@%@%@\n%@%@", str1, money, str2, type, point);
    } else {
        str = kStringFormat(@"%@%@\n%@%@", money, str2, type, point);
    }
    
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:str];
    
    if (money.floatValue > 0) {
        [attrStr addAttributes:@{NSForegroundColorAttributeName: kHEX(@"#F13519"), NSFontAttributeName: kUIFont(12)} range:[str rangeOfString:str1]];
    }
    
    [attrStr addAttributes:@{NSForegroundColorAttributeName: kHEX(@"#F13519"), NSFontAttributeName: kUIFont(12)} range:[str rangeOfString:str2]];
    
    [attrStr addAttributes:@{NSForegroundColorAttributeName: kHEX(@"#F13519"), NSFontAttributeName: kUIFont(21)} range:[str rangeOfString:money]];
    
    
    [attrStr addAttributes:@{NSForegroundColorAttributeName: kHEX(@"#1E1E1E"), NSFontAttributeName: kUIFont(12)} range:[str rangeOfString:type]];
    
    [attrStr addAttributes:@{NSForegroundColorAttributeName: kHEX(@"#1E1E1E"), NSFontAttributeName: kUIFont(10)} range:[str rangeOfString:point]];
    
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.alignment = NSTextAlignmentCenter;
    paragraphStyle.lineSpacing = 6;
    [attrStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, attrStr.length)];
    
    return attrStr;
    
}

- (NSMutableAttributedString *)rightAttr:(NSString *)count type:(NSString *)type {
    NSString *str2 = @"人";
    NSString *str = kStringFormat(@"%@%@\n%@",count,str2,type);
    
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:str];
    
    [attrStr addAttributes:@{NSForegroundColorAttributeName: kHEX(@"#F13519"), NSFontAttributeName: kUIFont(12)} range:[str rangeOfString:str2]];
    
    [attrStr addAttributes:@{NSForegroundColorAttributeName: kHEX(@"#F13519"), NSFontAttributeName: kUIFont(21)} range:[str rangeOfString:count]];
    
    [attrStr addAttributes:@{NSForegroundColorAttributeName: kHEX(@"#1E1E1E"), NSFontAttributeName: kUIFont(12)} range:[str rangeOfString:type]];
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.alignment = NSTextAlignmentCenter;
    paragraphStyle.lineSpacing = 6;
    [attrStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, attrStr.length)];
    return attrStr;
    
}

#pragma mark - viewBlock
- (void)viewBlock {
    XMWeakSelf(self);
    self.inviteShareView.clickBlock = ^(XMInviteShareType type) {
        XMStrongSelf(self);
        switch (type) {
            case XMInviteShareWX:
            {
                XMWeakSelf(self);
                [GKCover hideCoverWithHideBlock:^{
                    XMStrongSelf(self);
                    self.shareModel.share_type = XMShareTypeSession;
                    [[XMWXApiManager defaultManager] weChatShare:self.shareModel];
                }];
            }
                break;
            case XMInviteShareWX1:
            {
                XMWeakSelf(self);
                [GKCover hideCoverWithHideBlock:^{
                    XMStrongSelf(self);
                    self.shareModel.share_type = XMShareTypeTimeline;
                    [[XMWXApiManager defaultManager] weChatShare:self.shareModel];
                }];
            } break;
            case XMInviteShareQ:
            {
                XMWeakSelf(self);
                [GKCover hideCoverWithHideBlock:^{
                    XMStrongSelf(self);
                    QQApiNewsObject *newsObj = [QQApiNewsObject objectWithURL:kStringToUrl(self.shareModel.invite_link) title:self.shareModel.title description:self.shareModel.describe previewImageURL:kStringToUrl(self.shareModel.icons)];
                    SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:newsObj];
                    QQApiSendResultCode sent = [QQApiInterface sendReq:req];
                    NSLog(@"QQApiSendResultCode%ld", sent);
                }];
            } break;
            case XMInviteShareQ1:
            {
                if (![QQApiInterface isQQInstalled]) {
                    [MBProgressHUD showHUDMsg:@"请先安装QQ" toView:nil];
                    return;
                }
                
                if (![QQApiInterface isSupportShareToQQ]) {
                    [MBProgressHUD showHUDMsg:@"当前QQ版本不支持分享" toView:nil];
                    return;
                }
                XMWeakSelf(self);
                [GKCover hideCoverWithHideBlock:^{
                    XMStrongSelf(self);
                    QQApiNewsObject *newsObj = [QQApiNewsObject objectWithURL:kStringToUrl(self.shareModel.invite_link) title:self.shareModel.title description:self.shareModel.describe previewImageURL:kStringToUrl(self.shareModel.icons)];
                    SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:newsObj];
                    QQApiSendResultCode sent = [QQApiInterface SendReqToQZone:req];
                }];
            } break;
                
                break;
            case XMInviteShareHB:
                [self showInviteSaveView];
                break;
            default:
                break;
        }
    };
    
    self.saveView.saveBlock = ^(UIImage * _Nonnull img) {
        [MBProgressHUD showHUDActivityMsg:nil];
        [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
            [PHAssetChangeRequest creationRequestForAssetFromImage:img];
        } completionHandler:^(BOOL success, NSError * _Nullable error) {
            if (error) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [MBProgressHUD hideHUD];
                    [MBProgressHUD showHUDMsg:@"保存失败" toView:kWindow completionBlock:^{
                        [GKCover hideCover];
                    }];
                });
            } else {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [MBProgressHUD hideHUD];
                    [MBProgressHUD showHUDMsg:@"保存成功" toView:kWindow completionBlock:^{
                        [GKCover hideCover];
                    }];
                });
                
            }
        }];
    };
    
    self.realTipView.closeBlock = ^{
        [GKCover hideCover];
    };
    
    self.realTipView.realBlock = ^{
        XMStrongSelf(self);
        XMWeakSelf(self);
        [GKCover hideCoverWithHideBlock:^{
            XMStrongSelf(self);
            XMRealViewController *vc = [[XMRealViewController alloc] initWithNibName:kStringFromClass(XMRealViewController) bundle:nil];
            [self.navigationController pushViewController:vc animated:YES];
        }];
    };
    
    self.redResultView.sureBlock = ^{
        XMStrongSelf(self);
        XMWeakSelf(self);
        [GKCover hideCoverWithHideBlock:^{
            XMStrongSelf(self);
            [self inviteData];
        }];
    };
}

- (void)handleSendResult:(QQApiSendResultCode)sendResult {
    if (sendResult == EQQAPISENDSUCESS) {
        
    }
}

#pragma mark - Actions
- (IBAction)invite:(UIButton *)sender {
    [self showInviteShareView];
}

- (IBAction)redLeft:(UIButton *)sender {
    if (![self isReal]) {
        return;
    }
    
    if (!kUserModel.bind_wechat_status) {
        return;
    }
    
    XMBenefits_configContent *model;
    switch (sender.tag) {
        case 0:
            NSLog(@"0");
            model = [self.model.benefits_config.content safe_objectAtIndex:0];
            break;
        case 1:
            NSLog(@"1");
            model = [self.model.benefits_config.content safe_objectAtIndex:1];
            break;
            
        case 2:
            NSLog(@"2");
            model = [self.model.benefits_config.content safe_objectAtIndex:2];
            break;
        default:
            break;
    }
    
    if (model.state.intValue != 1) {
        return;
    }
    
    [MBProgressHUD showHUDActivityMsg:nil toView:kWindow];
    NSMutableDictionary *dic = @{
        @"users": model.users
    }.mutableCopy;
    
    [YHNetworkManager.sharedInstance postWithUrl:@"api/activity/invite/handle" parameters:dic completeBlock:^(XMResponseTip * _Nonnull tip, id  _Nullable result) {
        if (tip.success) {
            [MBProgressHUD hideHUD];
            self.redResultView.moneyLa.text = kStringFormat(@"恭喜获得%@元", result[@"reward_money"]);
            [self showRedResultView];
        }
    }];
    
}

- (IBAction)copy:(UIButton *)sender {
    [MBProgressHUD showHUDMsg:@"复制成功!" toView:nil];
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = self.shareModel.invite_code;
}

- (IBAction)detail:(UIButton *)sender {
    if (self.dataArray.count == 0) {
        self.tableView3.hidden = YES;
        self.collectionView.hidden = YES;
        self.noDataLa.hidden = NO;
    } else {
        self.tableView3.hidden = NO;
        self.collectionView.hidden = YES;
        self.noDataLa.hidden = YES;
    }
    
    self.bgViewH.constant = self.tableViewH + 180;
    
    self.leftLa.attributedText = [self leftAttr:_model.invitation_data.today.invite_money point:kStringFormat(@"%@积分", _model.invitation_data.today.invite_score) type:@"今日收益："];
    
    self.rightLa.attributedText = [self leftAttr:_model.invitation_data.total.invite_money point:kStringFormat(@"%@积分", _model.invitation_data.total.invite_score) type:@"总收益："];
    
    [UIView animateWithDuration:0.3 animations:^{
        self.lineImgV.centerX = self.incomeDetailBtn.centerX;
    }];
}

- (IBAction)inviteNum:(UIButton *)sender {
    if (self.dataArray.count == 0) {
        self.tableView3.hidden = YES;
        self.collectionView.hidden = YES;
        self.noDataLa.hidden = NO;
    } else {
        self.tableView3.hidden = YES;
        self.collectionView.hidden = NO;
        self.noDataLa.hidden = YES;
    }
    
    self.bgViewH.constant = self.collectH + 180;
    
    self.leftLa.attributedText = [self rightAttr:kStringFormat(@"%@", _model.invitation_data.today.invite_users) type:@"今日邀请"];
    self.rightLa.attributedText = [self rightAttr:kStringFormat(@"%@", _model.invitation_data.total.invite_users) type:@"总邀请"];
    
    [UIView animateWithDuration:0.3 animations:^{
        self.lineImgV.centerX = self.inviteNumBtn.centerX;
    }];
}

#pragma mark - UITableViewDataSource & UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == self.tableView1) {
        return self.model.activity_config.content.config_list.count;
    }
    if (tableView == self.tableView2) {
        return 2;
    }
    if (tableView == self.tableView3) {
        return self.dataArray.count;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == self.tableView2) {
        if (indexPath.row == 0) {
            return 60;
        }
        return 80;
    }
    return 40;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == self.tableView1) {
        XMInviteTableViewCell1 *cell = [tableView dequeueReusableCellWithIdentifier:kStringFromClass(XMInviteTableViewCell1)];
        XMActivity_configList *model = [self.model.activity_config.content.config_list safe_objectAtIndex:indexPath.row];
        cell.leftLa.text = model.index;
        cell.midLa.text = model.label;
        cell.rightLa.text = model.award;
        cell.currentBtn.hidden = model.state.intValue == 0;
        return cell;
    }
    
    if (tableView == self.tableView2) {
        XMXMInviteTableViewCell2 *cell = [tableView dequeueReusableCellWithIdentifier:kStringFromClass(XMXMInviteTableViewCell2)];
        if (indexPath.row == 0) {
            cell.numla.text = @"1";
            if (self.model.award_introduce.count > 0) {
                NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:[self.model.award_introduce firstObject].intro];
                // 创建NSMutableParagraphStyle，并设置行高
                NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
                paragraphStyle.alignment = NSTextAlignmentLeft;
                paragraphStyle.lineSpacing = 6; // 设置行高为10个点
                // 将行高属性添加到文本属性中
                [attributedText addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, attributedText.length)];
                cell.descLa.attributedText = attributedText;
            }
        } else {
            cell.numla.text = @"2";
            if (self.model.award_introduce.count > 1) {
                NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:[self.model.award_introduce lastObject].intro];
                // 创建NSMutableParagraphStyle，并设置行高
                NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
                paragraphStyle.alignment = NSTextAlignmentLeft;
                paragraphStyle.lineSpacing = 6; // 设置行高为10个点
                // 将行高属性添加到文本属性中
                [attributedText addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, attributedText.length)];
                cell.descLa.attributedText = attributedText;
            }
            
        }
        return cell;
    }
    
    XMXMInviteTableViewCell3 *cell = [tableView dequeueReusableCellWithIdentifier:kStringFromClass(XMXMInviteTableViewCell3)];
    XMUserModel *user = [self.dataArray safe_objectAtIndex:indexPath.row];
    cell.nameLa.text = user.nickname;
    cell.pointLa.text = kStringFormat(@"收益%@积分", user.benefit_score);
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return nil;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (self.dataArray.count == 0) {
        return 0;
    }
    return self.dataArray.count + 1;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (self.dataArray.count == 0) {
        return nil;
    }
    XMInviteCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kStringFromClass(XMInviteCollectionViewCell) forIndexPath:indexPath];
    if (indexPath.item == self.dataArray.count) {
        cell.nameLa.text = @"去邀请";
        cell.imgV.image = kGetImage(@"invite_add");
    } else {
        XMUserModel *user = [self.dataArray safe_objectAtIndex:indexPath.row];
        cell.nameLa.text = user.nickname;
        [cell.imgV sd_setImageWithURL:kStringToUrl(user.avatar.file_url)];
        kCornerRadius(cell.imgV, 29, 1, kHEX(@"#FF4D39"));
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.item == self.dataArray.count) {
        [self showInviteShareView];
    }
}

- (XMInviteRuleView *)inviteRuleView {
    if (!_inviteRuleView) {
        _inviteRuleView = [XMInviteRuleView viewFromXib];
        _inviteRuleView.size = CGSizeMake(kScreenWidth, kScreenHeight);
    }
    return _inviteRuleView;
}

- (void)showInviteRuleView {
    NSString *str = self.model.rules_introduce;
    NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:str];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.alignment = NSTextAlignmentLeft;
    paragraphStyle.lineSpacing = 6;
    [attributedText addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, attributedText.length)];
    [attributedText addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"PingFangSC-Regular" size:14] range:NSMakeRange(0, attributedText.length)];
    self.inviteRuleView.textView.attributedText = attributedText;
    [GKCover coverFrom:self.view contentView:self.inviteRuleView style:(GKCoverStyleTranslucent) showStyle:(GKCoverShowStyleCenter) showAnimStyle:(GKCoverShowAnimStyleNone) hideAnimStyle:(GKCoverHideAnimStyleNone) notClick:YES];
}

- (XMInviteShareView *)inviteShareView {
    if (!_inviteShareView) {
        _inviteShareView = [XMInviteShareView viewFromXib];
        _inviteShareView.size = CGSizeMake(kScreenWidth, kScreenHeight);
    }
    return _inviteShareView;
}

- (void)showInviteShareView{
    [GKCover coverFrom:self.view contentView:self.inviteShareView style:(GKCoverStyleTranslucent) showStyle:(GKCoverShowStyleCenter) showAnimStyle:(GKCoverShowAnimStyleNone) hideAnimStyle:(GKCoverHideAnimStyleNone) notClick:YES];
}

- (XMSaveInviteView *)saveView {
    if (!_saveView) {
        _saveView = [XMSaveInviteView viewFromXib];
        _saveView.size = CGSizeMake(kScreenWidth, kScreenHeight);
    }
    return _saveView;
}

- (void)showInviteSaveView {
    if ([GKCover hasCover]) {
        [GKCover hideCoverWithHideBlock:^{
            [GKCover coverFrom:self.view contentView:self.saveView style:(GKCoverStyleTranslucent) showStyle:(GKCoverShowStyleCenter) showAnimStyle:(GKCoverShowAnimStyleNone) hideAnimStyle:(GKCoverHideAnimStyleNone) notClick:YES];
        }];
    } else {
        [GKCover coverFrom:self.view contentView:self.saveView style:(GKCoverStyleTranslucent) showStyle:(GKCoverShowStyleCenter) showAnimStyle:(GKCoverShowAnimStyleNone) hideAnimStyle:(GKCoverHideAnimStyleNone) notClick:YES];
    }
    
}

- (BOOL)isReal {
    if (kUserModel.idcard_verify) {
        return YES;
    } else {
        [self showRealTipView];
        return NO;
    }
}

- (XMRealTipView *)realTipView {
    if (!_realTipView) {
        _realTipView = [XMRealTipView viewFromXib];
        _realTipView.size = CGSizeMake(kScreenWidth, kScreenHeight);
    }
    return _realTipView;
}

- (void)showRealTipView {
    [GKCover coverFrom:self.view contentView:self.realTipView style:(GKCoverStyleTranslucent) showStyle:(GKCoverShowStyleCenter) showAnimStyle:(GKCoverShowAnimStyleNone) hideAnimStyle:(GKCoverHideAnimStyleNone) notClick:YES];
}

- (XMInviteRedResultView *)redResultView {
    if (!_redResultView) {
        _redResultView = [XMInviteRedResultView viewFromXib];
        _redResultView.size = CGSizeMake(kScreenWidth, kScreenHeight);
    }
    return _redResultView;
}

- (void)showRedResultView {
    [GKCover coverFrom:self.view contentView:self.redResultView style:(GKCoverStyleTranslucent) showStyle:(GKCoverShowStyleCenter) showAnimStyle:(GKCoverShowAnimStyleNone) hideAnimStyle:(GKCoverHideAnimStyleNone) notClick:YES];
}


@end
